package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.vo.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@DubboService(version = "1.0.0")
public class RecommendUserApiImpl implements RecommendUserApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //今日佳人
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        Query query = Query.query(Criteria.where("toUserId")
                .is(userId))
                .with(Sort.by(Sort.Order.desc("score"))).limit(1);
        return this.mongoTemplate.findOne(query, RecommendUser.class);
    }

    //推荐列表
    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long userId, Integer pageNum, Integer pageSize) {
        //mongodb 的api 分页和封装
        PageRequest pageRequest = PageRequest.of(pageNum-1,pageSize,Sort.by(Sort.Order.desc("score")));
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(pageRequest);


        //TODO  列表中没有排除今日佳人
        RecommendUser recommendUser = this.queryWithMaxScore(userId);
        if (ObjectUtil.isNotEmpty(recommendUser)){
            query.addCriteria(Criteria.where("userId").ne(recommendUser.getUserId()));
        }

        List<RecommendUser> recommendUserList = this.mongoTemplate.find(query, RecommendUser.class);
        PageInfo<RecommendUser> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        if (CollUtil.isEmpty(recommendUserList)){
            return pageInfo;
        }

        pageInfo.setRecords(recommendUserList);
        //pageInfo.setTotal();  手机上下滑就不提供总条数了
        return pageInfo;
    }
}
